import { Room } from './sequelize';
// import { LiveSession } from './sequelize'; // 暂不实现session逻辑
import { Op } from 'sequelize';

export class RoomService {
  
  // 创建/更新房间
  async upsertRoom(
    roomId: string, 
    title?: string, 
    coverUrl?: string,
    streamerName?: string,
    streamerAvatar?: string,
    streamerDisplayId?: string,
    streamerShortId?: string,
    type?: string,
    weight?: number
  ) {
    return await Room.upsert({
      id: roomId, 
      title, 
      coverUrl, 
      streamerName, 
      streamerAvatar, 
      streamerDisplayId, 
      streamerShortId,
      type,
      weight
    });
  }

  // 获取房间信息
  async getRoom(roomId: string) {
    return await Room.findByPk(roomId, {
    });
  }

  // 获取房间当前活跃场次 (暂不实现)
  async getCurrentSession(roomId: string) {
    // TODO: session逻辑暂不实现
    return null;
  }

  // 删除房间
  async deleteRoom(roomId: string) {
    return await Room.destroy({
      where: { id: roomId }
    });
  }

  // 获取房间列表（分页）
  async getRooms(page: number = 1, limit: number = 30) {
    const offset = (page - 1) * limit;

    const { count, rows } = await Room.findAndCountAll({
      offset,
      limit,
      order: [['createdAt', 'DESC']],
      // include: [
      //   {
      //     model: LiveSession,
      //     as: 'sessions',
      //     where: { status: 1 },
      //     required: false,
      //     limit: 1,
      //     order: [['startTime', 'DESC']]
      //   }
      // ],
      distinct: true
    });
    
    return {
      rooms: rows,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    };
  }

  // 获取所有房间并按权重排序（用于轮询）
  async getAllRoomsOrderedByWeight() {
    return await Room.findAll({
      order: [
        ['weight', 'DESC'], // 权重高的在前
        ['createdAt', 'DESC'] // 权重相同时按创建时间排序
      ]
    });
  }
}
